package com.java.simple.study.juc.p7;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhoujunlin
 * @date 2022年08月06日 21:29
 * @desc
 */
@Slf4j(topic = "c.TestScheduleTask")
public class TestScheduleTask {

    public static void main(String[] args) {
        // 1. 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 2. 获取周六时间 本周六或者下周六。。。
        LocalDateTime targetTime = now.withHour(21).withMinute(38).withSecond(0).withNano(0).with(DayOfWeek.SATURDAY);
        if (now.compareTo(targetTime) > 0) {
            //如果当前时间>本周周六  必须找到下周周六
            targetTime = targetTime.plusWeeks(1);
        }

        // 3. 获取延迟时间
        long initialDelay = Duration.between(now, targetTime).toMillis();
        // 4. 周期为每周
        long period = 7 * 24 * 60 * 60 * 1000;

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            log.debug("running");
        }, initialDelay, period, TimeUnit.MILLISECONDS);
    }

}
